<?php
namespace app\member\model;

use app\BaseModel;
use app\massage\model\CarAtvRecord;
use app\massage\model\Order;
use app\member\info\PermissionMember;
use app\shop\model\AdminShopOrder;
use think\facade\Db;

class Member extends BaseModel
{


    //会员商品表  该表暂时不使用
    protected $name = 'longbing_card_v2_member_level';


//    protected $append = [
//
//        'level_content',
//
//        'level_top'
//
//    ];

    protected $resultSetType = 'collection';


    /**
     * @param $value
     * @param $data
     * @功能说明:获取等级名称
     * @author chenniang
     * @DataTime: 2020-07-16 09:47
     */
    public function getLevelContentAttr($value,$data){

        if(!empty($data['user_id'])&&!empty($data['uniacid'])){

            $level_model = new Level();

            $text  = $level_model->getUserLevel($data['user_id'],$data['uniacid']);

            return !empty($text)?$text['title']:'';

        }

    }

    /**
     * @param $value
     * @param $data
     * @功能说明:获取等级名称
     * @author chenniang
     * @DataTime: 2020-07-16 09:47
     */
    public function getLevelTopAttr($value,$data){

        if(!empty($data['user_id'])&&!empty($data['uniacid'])){

            $level_model = new Level();

            $text  = $level_model->getUserLevel($data['user_id'],$data['uniacid']);

            return !empty($text)?$text['top']:'';

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-11 11:36
     * @功能说明:
     *
     */
    public function memberUpdateInfo($dis){

        $data = $this->where($dis)->find();

        if(empty($data)){

            $this->memberAdd($dis);

            $data = $this->where($dis)->find();

        }

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-15 09:49
     * @功能说明:添加
     */
    public function memberAdd($data){

        $data['status']      = 1;

        $data['create_time'] = time();

        $data['update_time'] = time();

        $res = $this->insert($data);

        return $res;
    }




    /**
     * @author chenniang
     * @DataTime: 2020-04-26 17:08
     * @功能说明:详情
     */
    public function memberInfo($dis){

        $data = $this->alias('a')
                ->join('longbing_card_user b','a.user_id = b.id','left')
                ->where($dis)
                ->field(['a.*','b.nickName','b.avatarUrl','ifnull(a.growth,0) as growth','ifnull(a.integral,0) as integral'])
                ->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-26 17:08
     * @功能说明:详情
     */
    public function memberInfoIndex($dis){

        $data = $this->alias('a')
            ->join('longbing_card_user b','a.user_id = b.id','right')
            ->where($dis)
            ->field(['ifnull(a.over_time,0) as over_time','a.id','b.nickName','b.avatarUrl','ifnull(a.stored,0) as balance','ifnull(a.cash_stored,0) as cash_balance','ifnull(a.over_time,0) as over_time','ifnull(a.growth,0) as growth','ifnull(a.integral,0) as integral'])
            ->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-16 09:35
     * @功能说明:编辑
     */
    public function memberUpdate($dis,$data){

        $data['update_time'] = time();

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-19 13:50
     * @功能说明:会员列表
     */
    public function memberListV2(){



    }



    /**
     * @author chenniang
     * @DataTime: 2020-07-16 09:41
     * @功能说明:会员列表
     */

    public function memberList($dis,$where,$mapor,$page){


        $data = $this->alias('a')
                ->join('longbing_card_user b','a.user_id = b.id')
                ->where($dis)
                ->where(function ($query) use ($mapor){
                    $query->whereOr($mapor);
                })
                ->where(function ($query) use ($where){
                    $query->whereOr($where);
                })
                ->field(['a.*','b.nickName','b.id as user_id',])
                ->group('a.id')
                ->order(['a.create_time desc','a.id'])
                ->paginate($page)
                ->toArray();

        $order_model = new AdminShopOrder();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['member_phone'] = Db::name('longbing_card_user_phone')->where(['user_id'=>$v['user_id']])->value('phone');

                $diss = [];

                $diss[] = ['uniacid','=',$v['uniacid']];

                $diss[] = ['user_id','=',$v['user_id']];

                $diss[] = ['create_time','>',$v['create_time']];

                $diss[] = ['pay_status','=',1];
                //消费金额
                $v['price']     = $order_model->where($diss)->sum('total_price');
                //订单量
                $v['order_num'] = $order_model->where($diss)->count();

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-08 10:20
     * @功能说明:讲所有用户添加到会员表
     */
    public function memberInit($uniacid){

        $member_user = $this->where(['uniacid'=>$uniacid])->column('user_id');

        $no_member_user = Db::name('longbing_card_user')->where(['uniacid'=>$uniacid])->where('id','not in',$member_user)->column('id');

        if(!empty($no_member_user)){

            foreach ($no_member_user as $value){

                $dis = [

                    'uniacid' => $uniacid,

                    'user_id' => $value
                ];

                $this->getMemberInfo($dis);
            }

        }

        return true;
    }



    /**
     * @author chenniang
     * @DataTime: 2020-07-16 15:30
     * @功能说明:统计
     */
    public function listForm($id){

        $order_model = new \app\shop\model\Order();

        $car_order_model = new Order();

        $record_model = new CarAtvRecord();

        $dis[] = ['user_id','=',$id];

        $dis[] = ['pay_type','>',1];

//        $dis[] = ['create_time','>',$member['create_time']];
        //商城消费金额
        $shop_price = $order_model->where($dis)->sum('true_price');
        //商城订单量
        $shop_count = $order_model->where($dis)->count();
        //赛车订单
        $car_price  = $car_order_model->where($dis)->sum('pay_price');
        //赛车订单量
        $car_count  = $car_order_model->where($dis)->count();
        //活动订单
        $atv_price  = $record_model->where($dis)->sum('pay_price');
        //活动订单量
        $atv_count  = $record_model->where($dis)->count();

        $data = [

            'price' => round($shop_price+$car_price+$atv_price,2),

            'count' => round($shop_count+$car_count+$atv_count,2),
        ];

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-19 16:09
     * @功能说明:获取总的订单
     */
    public function totalOrder($user_id,$type=1){

        $order_model = new Order();

//        $dis = [
//
//            ''
//        ]

        if($type==1){




        }else{


        }







    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-28 09:44
     * @功能说明:用户信息
     */
    public function userInfo($user_id,$uniacid){

        $dis = [

            'b.id' => $user_id

        ];
        //用户信息
        $user_info   = $this->memberInfoIndex($dis);
        //等级模型
        $level_model = new Level();

        $user_info['now_level'] = $level_model->getUserLevel($user_id,$uniacid);
        //是否是会员
        $user_info['is_member']  = !empty($user_info['now_level'])?1:0;

        if(!empty($user_info['now_level'])&&$user_info['now_level']['top']==999){
            //下一级等级
            $user_info['next_level'] = [];

        }else{
            //下一级等级
            $user_info['next_level'] = $level_model->getMemberLevel($uniacid,$user_info['growth']);
        }

        return $user_info;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-31 09:16
     * @功能说明:更新会员
     */
    public function updateMember($order){

        $growth_model = new Growth();

        $level_model  = new Level();

        $integral_model = new Integral();

        $member_goods_model = new Goods();

        Db::startTrans();
            //还未升级以前的等级
           $level_start =  $level_model->getUserLevel($order['user_id'],$order['uniacid']);
            //如果空就不是会员
           $level_start = !empty($level_start['top'])?$level_start['top']:0;
            //普通会员给成长值,plus会员给时间
           $member_goods_model->ordertypeUpdate($order);
            //增加成长值
           $growth_model->incUserGrowth($order['id'],$order['user_id'],$order['uniacid']);
            //增加后的等级
           $level_end = $level_model->getUserLevel($order['user_id'],$order['uniacid']);

           $level_end = !empty($level_end['top'])?$level_end['top']:0;
           //普通会员升级礼包
           if($level_end>$level_start){

               $level_model->upUserRights($level_end,$order);

           }
           //增加积分
           $integral_model->incUserIntegral($order['id'],$order['user_id'],$order['uniacid']);

        Db::commit();

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-31 09:43
     * @功能说明:加减成长值
     */
    public function incDecGrowth($dis,$growth,$file = 'growth',$type = 0){

        if($type==0){

            $this->where($dis)->update([$file=>Db::raw("$file+$growth")]);

        }else{

            $this->where($dis)->update([$file=>Db::raw("$file-$growth")]);

        }

        return true;
    }

    /**
     * @param $dis
     * @功能说明:获取数据 没有就添加一条
     * @author chenniang
     * @DataTime: 2020-07-31 09:27
     */

    public function getMemberInfo($dis){

        $data = $this->where($dis)->find();

        if(empty($data)){

            $this->memberAdd($dis);

            $data = $this->where($dis)->find();

        }

        return $data->toArray();

    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-03 11:51
     * @功能说明:商品详情
     */
    public function goodsInfoMember($goods_id,$user_id,$uniacid){

        //会员权限
        $member_p = new PermissionMember($uniacid);
        //会员商品折扣模型
        $discount_goods_model = new DiscountGoods();
        //会员配置模型
        $member_config_model  = new Config();
        //会员等级模型
        $level_model          = new Level();

        $member_config  = $member_config_model->configInfo(['uniacid'=>$uniacid]);
        //sass端授权
        $member_auth    = $member_p->pAuth();
        //会员开关
        $data['member_auth'] = $member_config['status']==1?$member_auth:false;
        //会员商品折扣
        $data['goods_discount'] = $discount_goods_model->userGoodsDiscount($goods_id,$user_id,$uniacid);

        $data['goods_discount'] = $data['goods_discount']*10;
        //会员等级
        $level  = $level_model->getUserLevel($user_id,$uniacid);

        $data['level_title'] = !empty($level)?$level['title']:'';

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-04 09:30
     * @功能说明:会员购买的回调
     */

    public function memberPayResult($order){

        $config_model = new Config();
        //配置
        $config = $config_model->configInfo(['uniacid'=>$order['uniacid']]);

        if($config['status']==1){

            $level_model    = new Level();

            $integral_model = new Integral();

            $growth_model   = new Growth();
            //配置
            $config = $config_model->configInfo(['uniacid'=>$order['uniacid']]);
            //等级
            $level  = $level_model->getUserLevel($order['user_id'],$order['uniacid']);
            //每日限领积分
            $day_integral = $integral_model->dayIntegral($order['user_id'],$order['uniacid']);
            //赠送积分
            if(!empty($config['integral_cash'])){
                //积分
                $integral = $order['total_price']*$config['integral_cash'];
                //积分倍率
                $balance  = !empty($level['integral_switch'])?$level['integral']:1;
                //要加的积分
                $integral = $integral*$balance;
                //最终的积分
                $integral = is_numeric($day_integral)&&$day_integral<$integral?$day_integral:$integral;
                //添加积分记录
                $integral_model->integralUserAdd($order['user_id'],$integral,$order['uniacid'],1,1,$order['id']);

            }
            //每日限领成长值
            $day_growth = $growth_model->dayGrowth($order['user_id'],$order['uniacid']);
            //赠送增长值(金额)
            if(!empty($config['growth_cash'])&&!empty($level)){
                //成长值
                $growth_cash = intval($order['total_price']*$config['growth_cash']);
                //最终成长值
                $growth_cash = is_numeric($day_growth)&&$day_growth<$growth_cash?$day_growth:$growth_cash;
                //添加成长值记录
                $growth_model->addUserGrowth($order['uniacid'],$order['user_id'],$growth_cash,$order['id'],1);
            }
            //赠送增长值（订单） 只有会员才送
            if(!empty($config['growth_order'])&&!empty($level)){
                //成长值
                $growth_cash = intval($config['growth_order']);
                //最终成长值
                $growth_cash = is_numeric($day_growth)&&$day_growth<$growth_cash?$day_growth:$growth_cash;
                //添加成长值记录
                $growth_model->addUserGrowth($order['uniacid'],$order['user_id'],$growth_cash,$order['id'],1);
            }

        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-07 17:12
     * @功能说明:退款
     */
    public function refundOrder($order_id){

        $integral_model = new Integral();

        $growth_model   = new Growth();

        $dis = [

            'order_id' => $order_id
        ];

        $integral_model->where($dis)->update(['refund'=>1]);

        $growth_model->where($dis)->update(['refund'=>1]);

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-11 11:25
     * @功能说明:会员权限
     */
    public function getAuth($uniacid){

        $config_model = new Config();

        $config    = $config_model->configInfo(['uniacid'=>$uniacid]);

        $persisson = new PermissionMember($uniacid);

        $auth = $persisson->pAuth();

        $auth = $config['status']==1?$auth:false;

        return $auth;
    }














}